import os

import yaml
from appium import webdriver

from utils.adboperator import AdbOperator
from utils.constant import BASE_PATH

device_config_path = os.path.join(BASE_PATH, 'config', 'device_config.yaml')


class DeviceManager:
    def __init__(self, config_path=device_config_path):
        self.config_path = config_path
        self.config = self._load_config()
        self.adb_operator = AdbOperator()
        self.driver = self._init_driver()
        self.app_name = self.config['appium']['desired_caps']['appium:appWaitPackage']

    def _load_config(self):
        with open(self.config_path, 'r', encoding='utf-8') as file:
            return yaml.safe_load(file)

    def _init_driver(self):
        appium_server_url = self.config['appium']['server_url']
        desired_caps = self.config['appium']['desired_caps']
        print("Desired Capabilities:", desired_caps)
        try:
            driver = webdriver.Remote(appium_server_url, desired_caps)
            print("Driver initialized successfully.")
            return driver
        except Exception as e:
            print(f"Failed to initialize driver: {e}")
            return None

    def enter_app(self, package_name):
        """检查是否进入应用，如果没有则启动应用"""
        try:
            # 检查应用是否在前台运行
            result = self.adb_operator.run_shell_cmd(f"dumpsys window | findstr mCurrentFocus")
            if package_name not in result:
                print(f"App {package_name} is not running. Launching app...")
                launch_command = f"monkey -p {package_name} -c android.intent.category.LAUNCHER 1"
                self.adb_operator.run_shell_cmd(launch_command)
            else:
                print(f"App {package_name} is already running.")
        except Exception as e:
            print(f"Error checking app status: {e}")


if __name__ == '__main__':
    device_manager = DeviceManager()
    my_driver = device_manager.driver
    my_driver.find_element('xpath', '//*[@text="一键换机"]').click()
    my_driver.quit()
